package com.boot_reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@ResponseBody
@RestControllerAdvice(annotations = {RestControllerAdvice.class, Controller.class})
public class GlobaExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> exptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return Result.error(msg);
        }
        return Result.error("失败了");
    }

//    @ExceptionHandler(Exception.class)
//    public Result<String> save(Exception ex){
//        log.error(ex.getMessage());
//        if(ex.getMessage().contains("Duplicate entry")){
//            String[] split = ex.getMessage().split(" ");
//            String msg = split[2];
//            return Result.error(msg);
//        }
//        return Result.error("失败了");
//    }
@ExceptionHandler(CustomException.class)
public Result<String> exptionHandler(CustomException ex){
    log.error(ex.getMessage());
    return Result.error(ex.getMessage());
}
}
